/*
 * www.yiji.com Inc.
 * Copyright (c) 2015 All Rights Reserved
 */

/*
 * 修订记录:
 * chenlin@yiji.com 2015-12-10 21:44 创建
 *
 */
package com.zerone.pay.trade.web.controller.weixin;

import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 微信处理服务提供组件
 * @author chenlin@yiji.com
 */
@Component
public class WechatProcessProvider implements InitializingBean, ApplicationContextAware {
	
	private Logger logger = LoggerFactory.getLogger(WechatProcessProvider.class);
	
	private ApplicationContext context;
	
	private Map<String, WechatProcessor> processorMap = Maps.newHashMap();
	
	/**
	 * 处理调用入口
	 * @param request 微信请求
	 * @return 处理结果
	 */
	public String execute(HttpServletRequest request) {
		
		MumWechatListener wechat = new MumWechatListener(request, this);
		String result = wechat.execute();
		
		return result;
	}
	
	/**
	 * 根据key获取处理器
	 * @param key key
	 * @return 处理器
	 */
	public WechatProcessor processor(String key) {
		WechatProcessor processor = processorMap.get(key);
		
		logger.info("execute with processor:[{}],processor:[{}]", key, processor);
		
		return processor;
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		Map<String, WechatProcessor> processBeanMap = context.getBeansOfType(WechatProcessor.class);
		processBeanMap.forEach((key, processor) -> {
			Wechater wechater = processor.getClass().getAnnotation(Wechater.class);
			if (null == wechater) {
				throw new IllegalArgumentException(String.format("processor must tag with annotation Weachater:[%s]",
					processor.getClass()));
			}
			
			if (null == wechater.key() || "".equals(wechater.key())) {
				throw new IllegalArgumentException(String.format("Weachater processor must has a key:[%s]",
					processor.getClass()));
			}
			
			logger.debug("load wechat processor with key:[{}],processor:[{}]", key, processor.getClass());
			
			processorMap.put(wechater.key(), processor);
		});
	}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.context = applicationContext;
	}
}
